/*
 * @lc app=leetcode.cn id=643 lang=javascript
 *
 * [643] 子数组最大平均数 I
 */

// @lc code=start
/**
 * @param {number[]} nums
 * @param {number} k
 * @return {number}
 */
var findMaxAverage = function (nums, k) {
  const size = nums.length;
  let sum = 0;
  let result = Number.MIN_SAFE_INTEGER;
  for (let i = 0; i < size; i++) {
    if (i < k) {
      sum += nums[i];
      if (i === k - 1) {
        result = Math.max(result, sum / k);
      }
    } else {
      let prev = nums[i - k];
      sum = sum - prev + nums[i];
      result = Math.max(result, sum / k);
    }
  }

  return result;
};
// @lc code=end
